import numpy as np
from PIL import Image
import logging


def split_image_channels(image):
    """
    将图像分割为多个通道
    
    参数:
        image: numpy数组，表示输入图像
    
    返回:
        包含各个通道的列表
    """
    if len(image.shape) == 2:
        logging.warning("尝试分割单通道图像，返回原图作为唯一通道")
        return [image]
    
    channels = []
    for i in range(image.shape[2]):
        channel = image[:, :, i]
        channels.append(channel)
    
    logging.info(f"成功将图像分割为{len(channels)}个通道")
    return channels


def merge_image_channels(file_paths):
    """
    从多个单通道图像文件合并为一个多通道图像
    
    参数:
        file_paths: 包含图像文件路径的列表
    
    返回:
        numpy数组，表示合并后的多通道图像
    """
    if not file_paths:
        raise ValueError("至少需要一个图像文件")
    
    channels = []
    target_size = None
    
    for path in file_paths:
        try:
            img = Image.open(path)
            img_array = np.array(img)
            
            # 确保所有通道尺寸一致
            if target_size is None:
                target_size = img_array.shape[:2]
            elif img_array.shape[:2] != target_size:
                raise ValueError(f"图像尺寸不一致: {path}的尺寸为{img_array.shape[:2]}，期望{target_size}")
            
            # 确保是单通道
            if len(img_array.shape) > 2:
                img_array = img_array[:, :, 0]  # 取第一个通道
            
            channels.append(img_array)
        except Exception as e:
            logging.error(f"加载图像失败: {path}, 错误: {str(e)}")
            raise
    
    # 堆叠通道
    if len(channels) == 1:
        merged = channels[0]
    else:
        merged = np.stack(channels, axis=2)
    
    logging.info(f"成功合并{len(channels)}个通道为图像")
    return merged